/**
 * Copyright (C) 2011 Andrew C. Love (DNC) <dnc.app.sup@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.dnc.cloak.framework.model;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;


public class  ModelList <MODEL_TYPE extends Model> extends AbstractModel {
	
	private List<MODEL_TYPE> modelList;
	private List<MODEL_TYPE> modifiedList;
	private Class<?> modelClass;
	
	
	public ModelList(Class<?> modelClass) {
		this(UUID.randomUUID().toString(),modelClass);		
	}

	public ModelList(String ID, Class<?> modelClass) {
		super();
		this.setID(ID);
		this.modelList = Collections.synchronizedList(new ArrayList<MODEL_TYPE>());
		this.modifiedList = Collections.synchronizedList(new ArrayList<MODEL_TYPE>());
		this.modelClass = modelClass;
	}
	
	public boolean isDirty() {
		return (modifiedList.size() > 0);
		
	}
	public List<MODEL_TYPE> getModelList() {
		return modelList;
	}
	
	public void setModelList(List<MODEL_TYPE> modelList) {
		this.modelList = modelList;
	}

	public List<MODEL_TYPE> getModifiedList() {
		return modifiedList;
	}

	public void setModifiedList(List<MODEL_TYPE> modifiedList) {
		this.modifiedList = modifiedList;
	}	
	
	public void insert(MODEL_TYPE model){
		insert(model,true);
	}

	public void insert(MODEL_TYPE model, boolean resetCRUD){		
		if (resetCRUD) {
			model.setInsert(true);	
			model.setUpdate(false);			
			model.setDelete(false);
			this.getModifiedList().add(model);
		}		
				
		this.getModelList().add(model);				
	}	

	public void insert(List<MODEL_TYPE> insertList) {		
		insert(insertList,true);		
	}	

	public void insert(List<MODEL_TYPE> insertList, boolean resetCRUD) {
		
		for (MODEL_TYPE model : insertList) {
			insert(model,resetCRUD);
		}	
		
	}		
	
	public void delete(MODEL_TYPE model) {
		model.setDelete(true);
		this.getModifiedList().add(model);		
		this.getModelList().remove(model);		
	}	

	public void delete(List<MODEL_TYPE> deleteList) {
		for (MODEL_TYPE model : deleteList) {
			model.setDelete(true);
		}
			
		this.getModifiedList().addAll(deleteList);		
		this.getModelList().removeAll(deleteList);		
	}
	
	
	public void clear() {
		this.getModifiedList().clear();
		this.getModelList().clear();		
	}

	public Class<?> getModelClass() {
		return modelClass;
	}	
	
}
